/* eslint-disable no-param-reassign */
import React, { Component } from 'react';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
  Card,
  Button,
  Steps,
  Alert,
  Row,
  Col,
  Radio,
  DatePicker,
  Select,
  Input,
  message,
  Modal,
} from 'antd';
import moment from 'moment';
import { connect } from 'dva';
import router from 'umi/router';
import queryString from 'query-string';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import FooterToolbar from '@/components/FooterToolbar';
import StandardTable from '@/components/StandardTable';
import Customer from '../../components/Customer';
// import { checkPermissions } from '@/utils/authority';
import Supplier from '../../components/NsSupplier';
import Finish from './PayApplyFinish';
import StaticTable from './staticTable';

const { Step } = Steps;
const FormItem = Form.Item;
const { RangePicker } = DatePicker;
const { Option } = Select;

@Form.create()
@connect(({ loading, payapply }) => ({
  loading: loading.models.payapply,
  payapply,
}))
class PayApplySubmit extends Component {
  state = {
    payapplytype: 0,
    selectedRows: [],
    selectedRowKeys: [],
    current: 0,
    switchFlag: false,
    resultInfo: {},
    params: {},
  };

  tableSearchLayout = {
    labelCol: { xl: { span: 7 }, xxl: { span: 7 } },
    wrapperCol: { xl: { span: 17 }, xxl: { span: 17 } },
  };

  tableSearchLayout1 = {
    labelCol: { xl: { span: 8 }, xxl: { span: 8 } },
    wrapperCol: { xl: { span: 16 }, xxl: { span: 16 } },
  };

  componentDidMount() {
    const { dispatch } = this.props;
    this.initialData();
    dispatch({
      type: 'payapply/queryDictItemsByCodes',
      payload: ['PAY_FEES_WAY', 'BANK_ID'],
    });
    this.getReceive();
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'payapply/updateModelData',
      payload: {
        payApplySubmitData: {
          firstStep: {},
          secondStep: {},
        },
        switchColumnsList: {},
        businessData: [],
        stepFormFieldsValue: {},
        submitPageData: {
          list: [],
          pagination: {
            current: 1,
            pageSize: 10,
            total: 10,
          },
        },
      },
    });
  }

  // 获取初始化数据
  initialData = async () => {
    const { location, dispatch } = this.props;
    const { payapplytype } = queryString.parse(location.search);
    this.setState({ payapplytype });
    await dispatch({
      type: 'payapply/initialPageData',
      payload: payapplytype,
    });
    await this.getList();
  };

  // 获得接单方
  getReceive = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'payapply/fetchReceive',
      payload: {
        status: 2,
        type: 4,
      },
    });
  };

  // 列表查询
  getList = (currentPage = 1, pageSize = 10, isClear = true) => {
    const {
      dispatch,
      form,
      // payapply: {
      //   payApplySubmitData: { firstStep },
      // },
    } = this.props;
    const { switchFlag, payapplytype } = this.state;
    if (isClear) {
      this.setState({
        selectedRowKeys: [],
        selectedRows: [],
      });
    }
    // const searchProps = firstStep.searchList.map(item => item.prop);
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      dispatch({
        type: 'payapply/updateModelData',
        payload: { stepFormFieldsValue: fieldsValue },
      });

      const formFieldsValue = {};
      const start =
        (fieldsValue.dateArr &&
          fieldsValue.dateArr[0] &&
          fieldsValue.dateArr[0].format('YYYYMM')) ||
        null;
      const end =
        (fieldsValue.dateArr &&
          fieldsValue.dateArr[1] &&
          fieldsValue.dateArr[1].format('YYYYMM')) ||
        null;
      Object.keys(fieldsValue).forEach(key => {
        if (key === 'dateArr') {
          switch (payapplytype) {
            case '2':
              formFieldsValue.startYm = start;
              formFieldsValue.endYm = end;
              break;
            case '5':
              formFieldsValue.queryStartTime = start;
              formFieldsValue.queryEndTime = end;
              break;
            case '6':
              formFieldsValue.queryStartTime = start;
              formFieldsValue.queryEndTime = end;
              break;
            case '4':
              if (switchFlag) {
                formFieldsValue.creStartDate = start;
                formFieldsValue.creEndDate = end;
              } else {
                formFieldsValue.startYm = start;
                formFieldsValue.endYm = end;
              }
              break;
            default:
              formFieldsValue.startDate = start;
              formFieldsValue.endDate = end;
              break;
          }
        } else if (key !== 'radio') {
          formFieldsValue[key] = fieldsValue[key] === undefined ? null : fieldsValue[key];
        }
        delete formFieldsValue.dateArr;
      });
      const pageArg = { currentPage, pageSize };

      dispatch({
        type: 'payapply/fetchSubmitList',
        payload: {
          pageArg,
          params: {
            ...formFieldsValue,
          },
          payapplytype,
          switchFlag,
        },
      });
    });
  };

  handleSelectRows = (rows, rowKeys) => {
    this.setState({ selectedRows: rows, selectedRowKeys: rowKeys });
  };

  handleStandardTableChange = pagination => {
    this.getList(pagination.current, pagination.pageSize, false);
  };

  // 下一步
  // eslint-disable-next-line consistent-return
  next = () => {
    const {
      form,
      dispatch,
      payapply: {
        payApplySubmitData: { firstStep },
      },
    } = this.props;
    const { current, selectedRows, payapplytype, selectedRowKeys } = this.state;
    let tip = '';
    const paymentCs = {};
    let csFlag2;
    const csModalData = [];
    const paymentNs = {};
    let nsFlag4;
    let osFlag;
    if (!selectedRows.length) return message.warning('请至少选择一条数据');
    switch (payapplytype) {
      // 返款支付判断客服系统同一客户和员工
      case '1':
        selectedRows.forEach(item => {
          if (item.custId !== selectedRows[0].custId) {
            paymentCs.custFlag = true;
          }
          if (item.empId !== selectedRows[0].empId) {
            paymentCs.empFlag = true;
          }
        });
        if (paymentCs.empFlag) tip = '非同一员工的支付申请，不可同时提交';
        if (paymentCs.custFlag) tip = '非同一客户的支付申请，不可同时提交';
        break;
      case '2':
        // 判断客服系统客户费用退费
        selectedRows.forEach(item => {
          if (item.custId !== selectedRows[0].custId) {
            csFlag2 = false;
          }
          if (item.billState === '1') {
            csModalData.push(item);
          }
        });
        if (csFlag2) {
          tip = '非同一接单方，不可同时提交';
        }
        break;
      // 返款支付判断全国同一签约方和员工
      case '3':
        selectedRows.forEach(item => {
          if (item.ordSndrId !== selectedRows[0].ordSndrId) {
            paymentNs.ordSndrFlag = true;
          }
          if (item.empId !== selectedRows[0].empId) {
            paymentNs.empFlag = true;
          }
        });
        if (paymentNs.empFlag) tip = '非同一员工的支付申请，不可同时提交';
        if (paymentNs.ordSndrFlag) tip = '非同一签约方的支付申请，不可同时提交';
        break;
      // 全国付费账单支付
      case '4':
        selectedRows.forEach(item => {
          if (item.recvSuppId !== selectedRows[0].recvSuppId) {
            nsFlag4 = true;
          }
          if (item.ordSndrId !== selectedRows[0].ordSndrId) {
            nsFlag4 = true;
          }
        });
        if (nsFlag4) {
          tip = '非同一接单方，不可合并提交';
        }
        break;
      case '5':
      case '6':
        // 判断运行系统是否同一大库
        osFlag = selectedRows.some(item => {
          if (item.insAcco) {
            return item.insAcco !== selectedRows[0].insAcco;
          }
          if (item.accuAcco) {
            return item.accuAcco !== selectedRows[0].accuAcco;
          }
          return false;
        });
        if (osFlag) {
          tip = '非同一大库的账单，不可同时提交申请';
        }
        break;
      default:
        break;
    }
    if (tip.length) {
      return message.warning(tip);
    }
    // 如果当前客户下有待收费的客户账单
    if (csModalData.length) {
      return Modal.warning({
        title: '当前客户系统内存在未收费账单，不能提交退费申请',
        content: (
          <div>
            {csModalData.map(item => (
              <Row gutter={24} key={item.billId}>
                <Col span={8}>账单编号：{item.billNo}</Col>
                <Col span={8}>账单年月：{item.billYm}</Col>
                <Col span={8}>账单金额：{item.billAmo}</Col>
              </Row>
            ))}
          </div>
        ),
        okText: '关闭',
        okType: 'default',
        autoFocusButton: 'cancel',
        width: 700,
      });
    }
    let params = {};
    const feeTypeValue = form.getFieldsValue(['radio']);
    if (feeTypeValue.radio) {
      params.feeType = feeTypeValue.radio;
    } else {
      params.feeType = firstStep.searchListRadioValue;
    }
    params = {
      ...params,
      bizType: payapplytype,
      orderCodes: selectedRowKeys,
    };
    this.setState({
      params,
      current: current + 1,
    });
    dispatch({
      type: 'payapply/getSecond',
      payload: params,
    });
  };

  // 上一步
  prev = () => {
    const {
      payapply: {
        submitPageData: { pagination },
      },
    } = this.props;
    const { current } = this.state;
    this.setState(
      {
        current: current - 1,
      },
      () => {
        this.getList(pagination.current, pagination.pageSize, false);
      }
    );
  };

  close = () => {
    router.goBack();
  };

  // 获取表格的columns
  columnsRender = data => {
    if (!data) return [];
    return data.map((item, i) => ({
      title: item.label,
      dataIndex: item.prop,
      onCell: () => ({ style: { textAlign: item.cellTextAlign || 'left' } }),
      onHeaderCell: () => ({
        style: { fontWeight: 'bold', textAlign: item.headerTextAlign || 'left' },
      }),
      render: text => {
        switch (item.type) {
          case 'date':
            return moment(text).format('YYYY-MM-DD HH:mm');
          case 'dateYm':
            return moment(text).format('YYYY-MM');
          default:
            return text || '--';
        }
      },
      key: item.prop + i,
    }));
  };

  // 搜索框单选切换
  onChange = () => {
    const { switchFlag } = this.state;
    this.setState(
      {
        switchFlag: !switchFlag,
      },
      () => {
        this.getList();
      }
    );
  };

  // 切换取到的值
  getSwitchData = type => {
    const { switchFlag, payapplytype } = this.state;
    const {
      payapply: {
        payApplySubmitData: { firstStep },
        switchColumnsList,
      },
    } = this.props;
    if (switchFlag) {
      return switchColumnsList[type][`${type + payapplytype}`];
    }
    return firstStep[type];
  };

  // 提交
  submit = () => {
    const { params, current } = this.state;
    const {
      dispatch,
      form,
      payapply: {
        payApplySubmitData: { secondStep },
        payAmount,
      },
    } = this.props;
    form.validateFields((err, values) => {
      if (err) return;
      const formValues = {
        ...params,
        ...values,
      };
      if (!formValues.payeeType) formValues.payeeType = secondStep.value;
      formValues.actualAmount = payAmount;
      dispatch({
        type: 'payapply/insertFmPay',
        payload: formValues,
      }).then(data => {
        if (data) {
          this.setState({
            current: current + 1,
          });
          dispatch({
            type: 'payapply/fetchRrtData',
            payload: data,
          }).then(datas => {
            if (datas) {
              this.setState({
                resultInfo: datas,
              });
            }
          });
        }
      });
    });
  };

  // 日期改变
  onMonthChanges = value => {
    const { form } = this.props;
    form.setFieldsValue({
      dateArr: value,
    });
  };

  // 设置当前位置
  setCurrentstep = current => {
    this.setState({ current });
  };

  render() {
    const {
      payapply: {
        steps,
        payApplySubmitData: { firstStep, secondStep },
        searchListDataSource,
        submitPageData,
        businessData,
        switchColumnsList,
        stepFormFieldsValue,
        payAmount,
        receiveList,
      },
      form: { getFieldDecorator },
      loading,
    } = this.props;
    const {
      payapplytype,
      current,
      selectedRowKeys,
      selectedRows,
      switchFlag,
      resultInfo,
    } = this.state;
    const RadioGroup = Radio.Group;
    const columns = this.columnsRender(this.getSwitchData('columns'));
    const searchList = this.getSwitchData('searchList');
    const formFieldsValue = {};
    let pull = 0;
    const rowKey = switchFlag
      ? switchColumnsList.rowKey[`rowKey${payapplytype}`]
      : firstStep.rowKey;
    return (
      <PageHeaderWrapper>
        <Card>
          <Steps current={current} style={{ marginBottom: 28 }}>
            {steps.map(item => (
              <Step key={item.title} title={item.title} />
            ))}
          </Steps>
          <div className="steps-content">
            {current === 0 && (
              <div>
                {firstStep.tip && (
                  <Alert
                    message={firstStep.tip}
                    type="info"
                    showIcon
                    style={{ marginBottom: 20 }}
                  />
                )}
                <Form>
                  <Row gutter={16}>
                    {searchList &&
                      searchList.map(item => {
                        let content;
                        let span = 7;
                        switch (item.type) {
                          case 'select':
                            content = (
                              <Select
                                allowClear
                                showSearch
                                filterOption={(input, option) =>
                                  option.props.children
                                    .toLowerCase()
                                    .indexOf(input.toLowerCase()) >= 0
                                }
                                style={{ width: '100%' }}
                                placeholder="请选择"
                              >
                                {searchListDataSource[item.dataSource] &&
                                  searchListDataSource[item.dataSource].map(value => (
                                    <Option key={value.itemCode}>{value.itemName}</Option>
                                  ))}
                              </Select>
                            );
                            break;
                          case 'radio':
                            span = 9;
                            pull = 1;
                            content = (
                              <RadioGroup onChange={this.onChange} style={{ marginTop: 5 }}>
                                {item.dataSource &&
                                  item.dataSource.map(c => (
                                    <Radio value={c.itemCode} key={c.itemCode}>
                                      {c.itemName}
                                    </Radio>
                                  ))}
                              </RadioGroup>
                            );
                            break;
                          case 'date':
                            content = <RangePicker style={{ width: '100%' }} />;
                            break;
                          case 'dateYm':
                            content = (
                              <RangePicker
                                placeholder={['开始年月', '结束年月']}
                                format="YYYY-MM"
                                mode={['month', 'month']}
                                style={{ width: '100%' }}
                                onPanelChange={this.onMonthChanges}
                              />
                            );
                            break;
                          case 'supplier':
                            content = <Supplier />;
                            break;
                          case 'customer':
                            content = <Customer allowClear />;
                            break;
                          case 'recvSupp':
                            content = (
                              <Select
                                placeholder="请选择"
                                style={{ width: '100%' }}
                                allowClear
                                showSearch
                                optionFilterProp="children"
                              >
                                {receiveList.map(c => (
                                  <Option key={c.suppId} title={c.name}>
                                    {c.name}
                                  </Option>
                                ))}
                              </Select>
                            );
                            break;
                          default:
                            content = <Input placeholder="请输入" />;
                            break;
                        }
                        return (
                          <Col md={span} sm={24} key={item.prop} pull={pull}>
                            <FormItem label={item.label} {...this.tableSearchLayout}>
                              {getFieldDecorator(item.prop, {
                                initialValue:
                                  stepFormFieldsValue[item.prop] ||
                                  (item.initialValue && String(item.initialValue)),
                              })(content)}
                            </FormItem>
                          </Col>
                        );
                      })}
                    <Col md={1} sm={24} pull={pull}>
                      <div style={{ marginBottom: 24 }}>
                        <Button type="primary" onClick={() => this.getList()}>
                          查询
                        </Button>
                      </div>
                    </Col>
                  </Row>
                </Form>
                <StandardTable
                  selectedRows={selectedRows}
                  selectedRowKeys={selectedRowKeys}
                  loading={loading}
                  data={submitPageData}
                  rowKey={
                    switchFlag
                      ? switchColumnsList.rowKey[`rowKey${payapplytype}`]
                      : firstStep.rowKey
                  }
                  columns={columns}
                  onSelectRow={this.handleSelectRows}
                  onChange={this.handleStandardTableChange}
                />
                <Row style={{ justifyContent: 'center', marginTop: 30 }}>
                  <Button onClick={() => this.close()}>关闭</Button>
                  <Button style={{ marginLeft: 30 }} type="primary" onClick={() => this.next()}>
                    下一步
                  </Button>
                </Row>
              </div>
            )}
            {current === 1 && (
              <div>
                <Card
                  title={
                    <span style={{ fontWeight: 'bolder' }} id="sendInfor">
                      业务数据
                    </span>
                  }
                  bordered={false}
                >
                  <StaticTable
                    payapplytype={payapplytype}
                    businessData={businessData}
                    rowKey={rowKey}
                    columns={columns}
                  />
                </Card>
                <Card
                  title={
                    <span style={{ fontWeight: 'bolder' }} id="sendInfor">
                      收款人信息
                    </span>
                  }
                  bordered={false}
                >
                  <Form>
                    <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                      <Col md={8} sm={24}>
                        <FormItem label="收款人类型" {...this.tableSearchLayout1}>
                          {secondStep.type === 'radio' ? (
                            getFieldDecorator('payeeType', {
                              rules: [{ required: true, message: '请选择收款人类型' }],
                            })(
                              <RadioGroup style={{ marginTop: 5 }}>
                                {secondStep.dataSource &&
                                  secondStep.dataSource.map(c => (
                                    <Radio value={c.itemCode} key={c.itemCode}>
                                      {c.itemName}
                                    </Radio>
                                  ))}
                              </RadioGroup>
                            )
                          ) : (
                            <div style={{ marginTop: 5 }}>{secondStep.text}</div>
                          )}
                        </FormItem>
                      </Col>
                      <Col md={8} sm={24}>
                        <FormItem label="收款人名称" {...this.tableSearchLayout1}>
                          {getFieldDecorator('payee', {
                            initialValue: formFieldsValue.payee,
                            rules: [{ required: true, message: '请输入收款人名称' }],
                          })(
                            <Input placeholder="请输入" maxLength={100} style={{ width: '100%' }} />
                          )}
                        </FormItem>
                      </Col>
                      <Col md={8} sm={24}>
                        <FormItem label="收款银行" {...this.tableSearchLayout1}>
                          {getFieldDecorator('bankCode', {
                            initialValue: formFieldsValue.bankCode,
                          })(
                            <Select
                              allowClear
                              showSearch
                              filterOption={(input, option) =>
                                option.props.children.toLowerCase().indexOf(input.toLowerCase()) >=
                                0
                              }
                              style={{ width: '100%' }}
                              placeholder="请选择"
                            >
                              {searchListDataSource.BANK_ID.map(value => (
                                <Option key={value.itemCode} value={value.itemCode}>
                                  {value.itemName}
                                </Option>
                              ))}
                            </Select>
                          )}
                        </FormItem>
                      </Col>
                      <Col md={8} sm={24}>
                        <FormItem label="开户行" {...this.tableSearchLayout1}>
                          {getFieldDecorator('bankOfDepo', {
                            initialValue: formFieldsValue.bankOfDepo,
                            rules: [{ required: true, message: '请输入开户行' }],
                          })(
                            <Input placeholder="请输入" maxLength={100} style={{ width: '100%' }} />
                          )}
                        </FormItem>
                      </Col>
                      <Col md={8} sm={24}>
                        <FormItem label="收款账号" {...this.tableSearchLayout1}>
                          {getFieldDecorator('account', {
                            initialValue: formFieldsValue.account,
                            rules: [
                              {
                                required: true,
                                message: '请输入最大长度不超过25的数字',
                                pattern: /^\d{1,25}$/,
                              },
                            ],
                          })(
                            <Input placeholder="请输入" maxLength={25} style={{ width: '100%' }} />
                          )}
                        </FormItem>
                      </Col>
                      <Col md={8} sm={24}>
                        <FormItem label="支付金额(元)" {...this.tableSearchLayout1}>
                          <div style={{ marginTop: 5 }}>{payAmount}</div>
                        </FormItem>
                      </Col>
                    </Row>
                  </Form>
                  <Row style={{ justifyContent: 'center', marginTop: 30 }}>
                    <Button onClick={() => this.prev()}>上一步</Button>
                    <Button style={{ marginLeft: 30 }} type="primary" onClick={() => this.submit()}>
                      提交
                    </Button>
                  </Row>
                </Card>
              </div>
            )}
            {current === 2 && (
              <Finish title="完成" resultInfo={resultInfo} setCurrentstep={this.setCurrentstep} />
            )}
          </div>
          <FooterToolbar style={{ width: '100%' }}>
            <Button
              onClick={() => {
                router.goBack();
              }}
            >
              返回
            </Button>
          </FooterToolbar>
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default PayApplySubmit;
